<template>
  <div class="realEstate">
    <div class="layui-panel">
      <div class="p-12">
        <div class="title">里程上报</div>
        <div class="pt-6">
          <form class="layui-form" action="">
            <div class="layui-row">
              <div class="layui-col-xs3">
                <div class="layui-form-item">
                  <label class="layui-form-label label-width">车辆号码</label>
                  <div class="layui-input-inline layui-input-wrap">
                    <input
                      type="text"
                      name="licPlateNum"
                      autocomplete="off"
                      placeholder="请输入"
                      lay-affix="clear"
                      class="layui-input"
                    />
                  </div>
                </div>
              </div>
              <div class="layui-col-xs3">
                <div class="layui-form-item">
                  <label class="layui-form-label">上报月份</label>
                  <div class="layui-input-inline layui-input-wrap">
                    <div class="layui-input-prefix">
                      <i class="layui-icon layui-icon-date"></i>
                    </div>
                    <input
                      type="text"
                      name="reportingMonth"
                      id="reportingMonth_2"
                      lay-verify="date"
                      placeholder="请选择"
                      autocomplete="off"
                      format="yyyy年MM月"
                      class="layui-input input-100"
                    />
                  </div>
                </div>
              </div>
              <div class="layui-col-xs3">
                <div class="layui-form-item">
                  <label class="layui-form-label">所属部门</label>
                  <div class="layui-input-inline layui-input-wrap">
                    <input
                      type="text"
                      name="dept"
                      placeholder="请输入"
                      autocomplete="off"
                      lay-affix="clear"
                      class="layui-input"
                    />
                  </div>
                </div>
              </div>
              <div class="layui-col-xs3">
                <button
                  class="layui-btn layui-btn-normal"
                  lay-submit
                  lay-filter="mileage-search"
                  type="button"
                >
                  <i class="layui-icon layui-icon-down layui-icon-search"></i>
                  搜索
                </button>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
    <div class="layui-panel mt-20">
      <div class="flex-end mt-12 mr-12">
        <button
          type="button"
          class="layui-btn layui-bg-blue"
          lay-on="openDialog"
        >
          新增
        </button>
      </div>
      <div class="p-12">
        <table class="layui-hide" id="ID-table-demo-data"></table>
      </div>
    </div>
    <div id="barDemo" style="display: none">
      <div class="layui-clear-space">
        <a class="layui-btn layui-btn-xs layui-bg-blue" lay-event="edit">编辑</a>
        <a class="layui-btn layui-btn-xs layui-bg-blue" lay-event="del">删除</a>
      </div>
    </div>
    <addDialog v-show="false" ref="addDialog"></addDialog>
  </div>
</template>

<script>
import addDialog from "@/views/mileageReporting/components/report.vue";
import { addMileageReporting,editMileageReporting,delMileageReporting } from '@/api/real_estate_ledger'
export default {
  components: {
    addDialog,
  },
  data() {
    return {
      addOfEdit: "",
      departmentId: "",
      token: localStorage.getItem('foxnic-web')?.token || "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhbGwiLCJ1aWQiOiIxMTA1ODgzNDgxMDExNjU5MTEiLCJhdWQiOiJhZG1pbiIsImlzcyI6ImZlbG9yZC5jbiIsInR5cGUiOiJhY2Nlc3MiLCJleHAiOiIyMDI0LTAxLTI0IDA5OjM5OjExIiwiaWF0IjoiMjAyNC0wMS0yNCAwOTowOToxMSIsImp0aSI6IjI0NWE4ZWFiLWIzNGYtNDE1NS1hZDkzLWE1NDhiNGZjZjgwNyJ9.Gdm2A-J03HHdzVEQBTdA2zwROzhSNZwKmb9lmKXqipwT2yykAjf3LRSWj0k8VBHAwwEqV336qnVgFEBRpwQFhpb6JDLRn84X9xhfuiGUwOZ1PNpNl5gvIqqaNexdtQ__9u5m371DrdE4rg5qwpFHpUm1p0Cr3scAjvjCXhf4HnbT6kFd1jItP__9hao2qpM6McHMZMCBAvMNBsjYQfOb2mPsLzudzu-S-Aow5yFdp2SLRyv9UEe0ITqiYOFlSQkHcE4YMrjYuCK1-OD7YhOdwx6yTclPhrrgLs3tFL7cfhjVoASO1Jfinm4DfcIojp57VGSIUZCtbd0Qqf_fhH3-kw",
    }
  },
  mounted() {
    window.layui.use(["table", "form", "jquery","treeSelect"], () => {
      var table = window.layui.table;
      const form = window.layui.form;
      const util = window.layui.util;
      const layer = window.layui.layer;
      const laydate = window.layui.laydate;
      const treeSelect = window.layui.treeSelect;
      const $ = window.layui.jquery;
      // 初始化
      uploadFormValue.call(this);

      laydate.render({
        elem: "#reportingMonth",
        type: "month"
      });
      laydate.render({
        elem: "#reportingMonth_2",
        type: "month"
      });
      // 已知数据渲染
      const tableIns = table.render({
        elem: "#ID-table-demo-data",
        url:
          process.env.VUE_APP_BASE_API +
          "/service-eam/gf-mileage-reporting/query-paged-list",
        method: "post",
        headers: {
          Authorization:
            "Bearer " + this.token,
        },
        request: {
          //自定义 page  limit
          pageName: "pageIndex",
          limitName: "pageSize",
        },
        cols: [
          [
            //标题栏
            { field: "reportingMonth", title: "上报月份", width: 120, sort: true },
            { field: "licPlateNum", title: "车辆号码", width: 150 },
            { field: "lastMileage", title: "上次里程", width: 150 },
            { field: "currentMileage", title: "本次里程", width: 150 },
            { field: "remark", title: "备注", width: 150 },
            { field: "dept", title: "所属部门", width: 150 },
            { field: "registrant", title: "登记人", width: 150 },
            { field: "createTime", title: "登记时间"},
            {
              field: "right",
              title: "操作",
              width: 160,
              minWidth: 125,
              fixed: "right",
              toolbar: "#barDemo",
            },
          ],
        ],
        parseData: function (res) {
          return {
            code: res.code, //解析接口状态
            msg: res.message, //解析提示文本
            count: res.data.totalRowCount, //解析数据长度
            data: res.data.list, //解析数据列表
          };
        },
        //skin: 'line', // 表格风格
        //even: true,
        page: true, // 是否显示分页
        limits: [5, 10, 15],
        limit: 5, // 每页默认显示的数量
      });
      util.on("lay-on", {
        openDialog:  () => {
          $(".reset_from").click();
          this.addOfEdit = "add";
          this.departmentId = "";
          form.render();
          this.dialog = layer.open({
            title: "里程上报",
            type: 1,
            offset: "t",
            anim: 0,
            area: ["800px", "100%"],
            shade: 0.1,
            shadeClose: true,
            id: "ID-demo-layer-direction-t",
            content: $("#add_dialog"),
          });
        },
      });
      // 表单搜索
      form.on("submit(mileage-search)", async (data) => {
        const field = data.field;
        tableIns.reload({
          url:
            process.env.VUE_APP_BASE_API +
            "/service-eam/gf-mileage-reporting/query-paged-list",
          page: {
            pageIndex: 1,
          },
          where: field,
        });
      });
      /** 表单编辑 删除 */
      table.on("tool(ID-table-demo-data)", (obj) => {
        const data = obj.data;
        if (obj.event === "del") {
          const configDialog = layer.confirm(
            "确定删除吗",
            { icon: 3, title: "删除确认" },
            async function () {
              const res = await delMileageReporting(data.id);
              if (res.code === "00") {
                layer.msg("删除成功", { icon: 1 });
                layer.close(configDialog);
                tableIns.reload();
              } else {
                layer.msg("删除失败", { icon: 2 });
              }
            }
          );
        }
        if (obj.event === "edit") {
          this.addOfEdit = "edit";
          this.departmentId = "";
          this.dialog = layer.open({
            title: "里程上报编辑",
            type: 1,
            offset: "t",
            anim: 0,
            area: ["800px", "100%"],
            shade: 0.1,
            shadeClose: true,
            id: "ID-demo-layer-direction-t",
            content: $("#add_dialog"),
          });
          uploadFormValue.call(this,obj, data);
        }
      });
      /** 表单修改 新增 */
      function uploadFormValue(obj, data) {
        // 回显
        form.val("formTeacherFilter", data);
        // if(this.addOfEdit === 'edit' && data.deptId) {
        //   this.$refs.addDialog.echoData(data?.deptId)
        // }
        if (this.addOfEdit === "edit") {
          this.$refs.addDialog.echoData(data.deptId);
        }
        form.on("submit(submit_table)", async (res) => {
          let field = res.field;
          const newArr = {};
          for (let key in field) {
            if (field[key]) {
              newArr[key] = field[key];
            }
          }
          if (this.addOfEdit !== "edit") {
            newArr.deptId = this.departmentId;
            newArr.dept = this.selectName
            const result = await addMileageReporting(newArr);
            if (result.code === "00") {
              layer.msg("新增成功", { icon: 1 });
              layer.close(this.dialog);
              tableIns.reload();
            } else {
              layer.msg("新增失败", { icon: 2 });
            }
            return;
          }
          newArr.id = data.id;
          newArr.deptId = this.departmentId || newArr.deptId;
          newArr.dept = this.selectName || newArr.dept
          const result = await editMileageReporting(newArr);
          if (result.code === "00") {
            layer.msg("修改成功", { icon: 1 });
            layer.close(this.dialog);
            tableIns.reload();
          } else {
            layer.msg("修改失败", { icon: 2 });
          }
        });
      }
        // 树形下拉组件
    treeSelect.render({
      // 选择器
      elem: "#tree4",
      // 数据
      data:
        process.env.VUE_APP_BASE_API +
        '/service-hrm/hrm-organization/query-nodes?isLoadAllDescendants=1&targetType="com"',
      // 异步加载方式：get/post，默认get
      type: "post",
      headers: {
        Authorization: "Bearer " + this.token,
      },
      style: {
        folder: {
          // 父节点图标
          enable: true, // 是否开启：true/false
        },
        line: {
          // 连接线
          enable: true, // 是否开启：true/false
        },
      },
      // 占位符
      placeholder: "请选择",
      // 是否开启搜索功能：true/false，默认false
      search: true,
      // 点击回调
      click: (d) => {
        this.departmentId = d.current.id;
        this.selectName = d.current.name
      },
      // 加载完成后的回调函数
      success: (d) => {
        //             // 选中节点，根据id筛选
        // if (this.addOfEdit === "edit") {
        //   treeSelect.checkNode("tree1", this.departmentId);
        // }
      },
    });
      /** 弹框取消按钮监听 */
      $('.cancel').on('click',() => {
        layer.close(this.dialog)
      })
      form.render();
    });
  },
};
</script>

<style scoped lang="scss">
.realEstate {
  .layui-input-inline {
    width: 150px;
  }
}
.title {
  font-size: 16px;
  color: #000000;
}

.label-width {
  width: 100px;
}

.p-12 {
  padding: 12px;
}

.pt-6 {
  padding-top: 6px;
}

.mt-20 {
  margin-top: 20px;
}
</style>
